package com.example.aop;

import com.example.mapper.OperateLogMapper;
import com.example.pojo.OperateLog;
import com.example.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.anno.Log)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();//记录开始时间
        Object result = pjp.proceed();//执行目标方法
        long end = System.currentTimeMillis();//记录结束时间

        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getUserId());//操作员工号
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setMethodParams(pjp.getArgs().toString());
        operateLog.setReturnValue(result!=null?result.toString():"void");
        operateLog.setCostTime(end-start);

        log.info("操作日志:{}",operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }

    private Integer getUserId() {
        return CurrentHolder.getCurrentId();//获取线程中保存的员工号
    }
}
